<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use Gregwar\Captcha\CaptchaBuilder;
use Myredis\Myredis;
use kuange\qqconnect\QC;
use app\index\controller\Unlogin;
use app\index\model\xoUser;
class Login extends Controller
{
    /**
     * 加载登录界面
     * @return \think\response\View
     */
    public function index()
    {
        return view('index', [
            'title' => '登录'
        ]);
    }

    /**
     * 处理账号密码登录
     * @return \think\response\View
     */
    public function dologin(Request $request)
    {
        //验证数据是否来自post传输方式
        if (!Request::instance()->isPost()) {
            return $this->error('小伙子迷路了呦', url('index/login/index'));
        }
        $tel = Request::instance()->post('phone');
        $pwd = Request::instance()->post('pass');
        $data = Myredis::hget('userLogin', $tel);
        $info = [
            'tel' => $tel,
            'pwd' => md5($pwd),
            'status' => 1
        ];
        //验证数据与redis中的数据是否一致
        if ($data && ($tel == $data['tel'] && md5($pwd) == $data['pwd'] && $data['status'] == 1)) {
            Db::table('xo_user')->where('tel', $tel)->update(['login_time' => time()]);
            //redis 查询出数据 存入session 登录成功
            Session::set('tel', $data['tel']);
            //生成一个唯一的token存在session和redis中
            $token = time() . mt_rand(1, 1000000);
            Session::set('token', $token);
            MyRedis::set($tel . 'token', $token);
            return $this->success('登录成功', url('index/index/index'));
        } else {
            //数据与redis不一致则查询数据库
            $res = Db::table('xo_user')->where($info)->field(['nickname', 'id', 'icon'])->find();
            if ($res) {
                //数据库能查到则存入session 将redis更新  登录成功
                Session::set('name', $res['nickname']);
                Session::set('uid', $res['id']);
                Session::set('icon', $res['icon']);
                Session::set('tel', $res['tel']);
                Myredis::hset('userLogin', $tel, $info);
                Db::table('xo_user')->where('tel', $tel)->update(['login_time' => time()]);
                $token = time() . mt_rand(1, 1000000);
                Session::set('token', $token);
                MyRedis::set($tel . 'token', $token);
                return $this->success('登录成功', url('index/index/index'));
            } else {
                //redis和数据库都查询不到则失败
                return $this->error('登录失败');
            }
        }
    }


    /**
     * 处理短信登录
     */
    public function msgLogin()
    {
        //验证数据是否来自post传输方式
        if (!Request::instance()->isPost()) {
            return $this->error('小伙子,是不是迷路了', url('index/index/index'));
        }
        //接受post数据
        $tel = Request::instance()->post('sphone');
        $telcode = Request::instance()->post('telcode');
        $pCode = Myredis::get($tel . 'telCode');
        //判断验证码是否正确
        if ($telcode != $pCode) {
            return $this->error('验证码输入错误,请重试');
        }
        //根据Tel查询数据库判断是否已存在
        $res = Myredis::hget('userLogin', $tel);
        if ($res && ($res['status'] == 1)) {
            Session::set('tel', $tel);
            $token = time() . mt_rand(1, 1000000);
            Session::set('token', $token);
            MyRedis::set($tel . 'token', $token);
            Db::table('xo_user')->where('tel', $tel)->update(['login_time' => time()]);
            return $this->success('登录成功', url('index/index/index'));
        } else {
            $res = Db::table('xo_user')->where([
                'tel' => $tel,
                'status' => 1
            ])->find();
            if ($res > 0) {
                Session::set('name', $res['nickname']);
                Session::set('uid', $res['id']);
                Session::set('tel', $tel);
                $token = time() . mt_rand(1, 1000000);
                Session::set('token', $token);
                MyRedis::set($tel . 'token', $token);
                return $this->success('登录成功', url('index/index/index'));
            } else {
                return $this->error('登录失败', url('index/index/index'));
            }
        }

    }

    /*
     * 处理邮箱登录
     */
    public function doemaillogin()
    {
       if(!Request::instance()->isPost()){
           return $this->redirect('index/error/index');
       }
        $data['email'] = Request::instance()->post('email');
        $data['pwd']=md5(Request::instance()->post('pwd'));
        $data['status']=1;
        $user = new xoUser();
        $res = $user->get($data);
        if(!empty($res)){
            Session::set('name', $res['nickname']);
            Session::set('uid', $res['id']);
            Session::set('email', $res['email']);
            //生成一个唯一的token存在session和redis中
            $token = time() . mt_rand(1, 1000000);
            Session::set('token', $token);
            MyRedis::set($res->email . 'token', $token);
            return $this->success('登录成功', url('index/index/index'));
        }else{
            return $this->error('登录失败', url('index/index/index'));
        }

    }
    /**
     * 退出登录
     */
    public function outlogin()
    {
        $data = Session::clear();
        $res = Myredis::del(Request::instance()->session('tel') . 'token');
        if($data && $res){
            return $this->success('退出成功', url('index/index/index'));
        }else{
            return $this->success('退出成功', url('index/index/index'));
        }
    }

    /**
     * 处理发送短信
     * @return array|void
     */
    public function domsg(Request $request)
    {
        //判断是否来自 ajax
        if (!Request::instance()->isAjax()) {
            return $this->error('小伙子,是不是迷路了', url('index/index/index'));
        }
        $telNum = Request::instance()->post('phone');
        $num = rand(100000, 999900);
        $res = $this->sendTemplateSMS($telNum, array($num, '5'), "1");
        Myredis::setex($telNum . 'telCode', 300, $num);
        //根据返回的状态码验证响应是否发送成功
        if ($res == '000000') {
            //短信发送成功将验证码存入session 等待验证
            echo 111;
            $data = [
                'status' => true,
                'info' => '发送成功',
            ];
        } elseif ($res == '160038') {
            $data = [
                'status' => false,
                'info' => '发送频繁,歇一会'
            ];
        } else {
            $data = [
                'status' => false,
                'info' => '发送失败'
            ];
        }
        return $data;
    }

    /**
     * 验证手机是否存在
     */
    public function isphone(Request $request)
    {
        //判断是否来自 ajax
        if (!Request::instance()->isAjax()) {
            return $this->error('小伙子,是不是迷路了', url('index/index/index'));
        }
        //接受post 数据
        $tel = Request::instance()->post('phone');
        //查询
        $res = Db::table('xo_user')->where('tel', $tel)->find();
        if ($res) {
            $data = ['status' => true];
        } else {
            $data = ['status' => false];
        };
        return json($data);
    }

    /**
     * 处理图片验证码刷新
     * @return \think\response\Json
     */
    public function imgCode()
    {
        $builder = new CaptchaBuilder;
        $builder->build();
        $str = $builder->getPhrase();
        //设置图片存储路径
        $builder->save('./static/out.jpg');
        //存入数组返回前端
        $data['str'] = $str;
        $data['src'] = '/static/out.jpg';
        return json($data);
    }

    /*
     * 调用qq接口
     */
    public function qqlogin()
    {
        $qc = new QC();
        return redirect($qc->qq_login());
    }


    public function qqcallback(Request $request)
    {
        $code = $request->get();
        // Step3：通过Authorization Code获取Access Token
        $token_url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101498294&client_secret=8aa50d405c9dcf9c56845f65a0da112f&code=' . $code['code'] . '&state=falitu&redirect_uri=http://www.xxoa.top/qqcallback';

        $token_res = https_request($token_url);
        $data = explode('&', $token_res);
        $data = explode('=', $data[0]);

        $token = $data[1];

        // Step4：使用Access Token来获取用户的OpenID
        $openid_url = 'https://graph.qq.com/oauth2.0/me?access_token=' . $token;

        $openid_res = https_request($openid_url);
        if (strpos($openid_res, "callback") !== false) {
            $lpos = strpos($openid_res, "(");
            $rpos = strrpos($openid_res, ")");
            $openid_res = substr($openid_res, $lpos + 1, $rpos - $lpos - 1);
            $msg = json_decode($openid_res, true);

        }
        $openid = $msg['openid'];

        $result = Db::name('xo_user')->field('password',true)->where('openid', $openid)->find();
        if (empty($result)) {

            return view('qq',['openid'=>$openid]);
        }else{
            Session::set('name', $result['nickname']);
            Session::set('uid', $result['id']);
            Session::set('icon', $result['icon']);
            Session::set('tel', $result['tel']);
            $token = time() . mt_rand(1, 1000000);
            Session::set('token', $token);
            MyRedis::set($tel . 'token', $token);
            $this->success('登录成功', 'http://www.xxoa.top');
        }

    }

}
